import type {Rule} from 'ant-design-vue/es/form'
import {VALIDATION} from '@/constants/messages'

// 验证规则构建器
export const Rules = {
    required: (message?: string): Rule => ({
        required: true,
        message: message || VALIDATION.REQUIRED,
        trigger: 'blur'
    }),
    email: (message = '请输入正确的邮箱'): Rule => ({
        type: 'email',
        message,
        trigger: 'blur'
    }),
    length: (min: number, max: number, message?: string): Rule => ({
        min,
        max,
        message: message || VALIDATION.RANGE_LENGTH(min, max),
        trigger: 'blur'
    }),
    minLength: (min: number, message?: string): Rule => ({
        min,
        message: message || VALIDATION.MIN_LENGTH(min),
        trigger: 'blur'
    }),
    maxLength: (max: number, message?: string): Rule => ({
        max,
        message: message || VALIDATION.MAX_LENGTH(max),
        trigger: 'blur'
    }),
    pattern: (pattern: RegExp, message: string): Rule => ({
        pattern,
        message,
        trigger: 'blur'
    }),
    validator: (fn: (value: any) => string | Promise<void>, trigger: 'blur' | 'change' = 'blur'): Rule => ({
        validator: (_, value) => {
            const result = fn(value)
            return typeof result === 'string' ? Promise.reject(result) : Promise.resolve()
        },
        trigger
    })
}

// 表单规则
export const FormRules = {
    userAccount: [
        Rules.required('请输入账号'),
        Rules.length(3, 16, '账号长度为3-16个字符'),
        Rules.pattern(/^[a-zA-Z0-9_]+$/, '账号只能包含字母、数字和下划线')
    ],
    userName: [
        Rules.required('请输入昵称'),
        Rules.length(2, 20, '昵称长度为2-20个字符')
    ],
    email: [
        Rules.required('请输入邮箱'),
        Rules.email()
    ],
    password: [
        Rules.required('请输入密码'),
        Rules.length(6, 20, '密码长度为6-20个字符')
    ],
    captcha: [
        Rules.required('请输入验证码'),
        Rules.pattern(/^\d{6}$/, '验证码为6位数字')
    ],
    pictureName: [
        Rules.required('请输入图片名称'),
        Rules.length(1, 100, '图片名称长度为1-100个字符')
    ],
    introduction: [
        Rules.maxLength(500, '简介长度不能超过500个字符')
    ],
    spaceName: [
        Rules.required('请输入空间名称'),
        Rules.length(2, 50, '空间名称长度为2-50个字符')
    ]
}

// 密码确认验证器
export const createConfirmPasswordRule = (formData: any, passwordField = 'userPassword') => ({
    validator: (_: any, value: string) => {
        if (!value) return Promise.reject('请确认密码')
        if (value !== formData[passwordField]) return Promise.reject('两次输入的密码不一致')
        return Promise.resolve()
    },
    trigger: 'blur'
})

// 验证工具函数
export const validate = {
    email: (email: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email),
    password: (password: string) => password.length >= 6 && password.length <= 20,
    required: (value: any) => !!value && String(value).trim() !== '',
    length: (value: string, min: number, max: number) => value.length >= min && value.length <= max
}
